package cn.daomeng.firebird.core.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Pattern;

/**
 * @description: SSO Client工具类
 * @author: wangcheng04
 * @create: 2019-03-08 17:25
 **/

public class CalorieSsoUtils {

    public CalorieSsoUtils() {

    }


    public static String getRedirectUrlOnLoginOut(HttpServletRequest httpServletRequest, String casAppKey,
                                                  String casLogoutUrl, String webHomePath) throws MalformedURLException, UnsupportedEncodingException {
        URL url = new URL(httpServletRequest.getRequestURL().toString());
        String redirectUrl = url.getProtocol() + "://" + url.getAuthority() + webHomePath;
        redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        return casLogoutUrl + "?appId=" + casAppKey + "&redirectUrl=" + redirectUrl;
    }

    /**
     * 通配符模式
     * @param whitePath - 白名单地址
     * @param servletPath - 请求地址
     * @return
     */
    public static boolean isWhiteEquals(String whitePath, String servletPath) {
        String regPath = getRegPath(whitePath);
        return Pattern.compile(regPath).matcher(servletPath).matches();
    }

    /**
     * 将通配符表达式转化为正则表达式
     * @param path
     * @return
     */
    private static String getRegPath(String path) {
        char[] chars = path.toCharArray();
        int len = chars.length;
        StringBuilder sb = new StringBuilder();
        boolean preX = false;
        for(int i=0;i<len;i++){
            //遇到*字符
            if (chars[i] == '*'){
                //如果是第二次遇到*，则将**替换成.*
                if (preX){
                    sb.append(".*");
                    preX = false;
                //如果是遇到单星，且单星是最后一个字符，则直接将*转成[^/]*
                }else if(i+1 == len){
                    sb.append("[^/]*");
                //否则单星后面还有字符，则不做任何动作，下一把再做动作
                }else{
                    preX = true;
                    continue;
                }
            //遇到非*字符
            }else{
                //如果上一把是*，则先把上一把的*对应的[^/]*添进来
                if (preX){
                    sb.append("[^/]*");
                    preX = false;
                }
                //接着判断当前字符是不是?，是的话替换成.
                if (chars[i] == '?'){
                    sb.append('.');
                //不是?的话，则就是普通字符，直接添进来
                }else{
                    sb.append(chars[i]);
                }
            }
        }
        return sb.toString();
    }
}
